//
//  AppDelegate.m
//  VivaModa
//
//  Created by Owly MacBook on 01.02.13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "AppDelegate.h"
#import "tab_Catalog.h"
#import "tab_Search.h"
#import "tab_Basket.h"
#import "tab_Info.h"
#include <sys/xattr.h>
#import <QuartzCore/QuartzCore.h>
#import "RNBlurModalView.h"



#define LIBRARY [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]


@implementation AppDelegate
@synthesize tabbar = _tabbar;


UIViewController *c_catalog,*c_search,*c_backet,*c_info;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self createAllDirectory];
    
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
   
    NSString* nib_catalog;
    NSString* nib_search;
    NSString* nib_basket;
    NSString* nib_info;

    
    if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
    {
        nib_catalog = @"tab_Catalog_iPad";
        nib_search = @"tab_Search_iPad";
        nib_basket = @"tab_Basket_iPad";
        nib_info = @"tab_Info_iPad";
    }else{
        nib_catalog = @"tab_Catalog";
        nib_search = @"tab_Search";
        nib_basket = @"tab_Basket";
        nib_info = @"tab_Info";
    }
    
    
    
    
    c_catalog = [[UINavigationController alloc] initWithRootViewController:[[tab_Catalog alloc] initWithNibName:nib_catalog bundle:nil]];
    c_search = [[UINavigationController alloc] initWithRootViewController:[[tab_Search alloc] initWithNibName:nib_search bundle:nil]];
    c_backet = [[UINavigationController alloc] initWithRootViewController:[[tab_Basket alloc] initWithNibName:nib_basket bundle:nil]];
    c_info = [[UINavigationController alloc] initWithRootViewController:[[tab_Info alloc] initWithNibName:nib_info bundle:nil]];
    
    
    
    //c_catalog.tabBarItem.title = @"Каталог";
    //c_search.tabBarItem.title = @"Поиск";
    //c_backet.tabBarItem.title = @"Корзина";
    //c_info.tabBarItem.title = @"Информация";
    
    self.tabbar = [[UITabBarController alloc] init];
    self.tabbar.viewControllers = [NSArray arrayWithObjects:c_catalog, c_search,c_backet, c_info, nil];
    [self setTabbarImage];
    [self changeBackgroundTabbar];
    
    //UITabBarItem *tbi = (UITabBarItem *)[self.tabbar.tabBar.items objectAtIndex:2];
    //tbi.badgeValue = @"2";
    //[self getBasketBadgeValue];
    //[self setBasketBadgeValue:4];
    [[Singleton sharedMySingleton] setBadge];
    [Singleton sharedMySingleton].neadCheckLogin = NO;
    [[Singleton sharedMySingleton] checkUser];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = self.tabbar;
    
    
    [self.window makeKeyAndVisible];
    //[self performSelector:@selector(onDemoButton) withObject:nil afterDelay:2];
    //[self addSubview];
    return YES;
}




-(void)setBasketBadgeValue:(int)value{
    UITabBarItem *tbi = (UITabBarItem *)[self.tabbar.tabBar.items objectAtIndex:2];
    if (value==0) {
        tbi.badgeValue = nil;
    }else{
        tbi.badgeValue = [NSString stringWithFormat:@"%i",value];
    }
    
    [self getBasketBadgeValue];
}


-(int)getBasketBadgeValue{
    UITabBarItem *tbi = (UITabBarItem *)[self.tabbar.tabBar.items objectAtIndex:2];
    
    if (tbi.badgeValue == nil) {
        return 0;
    }else{
        return [tbi.badgeValue integerValue];
    }
}




-(void)addSubview{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.2;
    [self.window addSubview:view];
}



/*
- (void) onDemoButton {
    BOOL useCustomView = NO;
    RNBlurModalView *modal;
    if (useCustomView) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        view.backgroundColor = [UIColor redColor];
        view.layer.cornerRadius = 5.f;
        view.layer.borderColor = [UIColor blackColor].CGColor;
        view.layer.borderWidth = 5.f;
        
        modal = [[RNBlurModalView alloc] initWithView:view];
    }
    else {
        modal = [[RNBlurModalView alloc] initWithTitle:@"Ошибка подключения Internet!" message:@"Для запуска приложения необходимо Internet соединение!"];
    }
    [modal show];
}
*/






-(void)setTabbarImage{
    UIImage *selectedImage0     = [UIImage imageNamed:@"tab_catalog_active.png"];
    UIImage *unselectedImage0   = [UIImage imageNamed:@"tab_catalog.png"];
    
    UIImage *selectedImage1     = [UIImage imageNamed:@"tab_search_active.png"];
    UIImage *unselectedImage1   = [UIImage imageNamed:@"tab_search.png"];
    
    UIImage *selectedImage2     = [UIImage imageNamed:@"tab_basket_active.png"];
    UIImage *unselectedImage2   = [UIImage imageNamed:@"tab_basket.png"];
    
    UIImage *selectedImage3     = [UIImage imageNamed:@"tab_info_active.png"];
    UIImage *unselectedImage3   = [UIImage imageNamed:@"tab_info.png"];
    
    
    UITabBar     *tabBar = self.tabbar.tabBar;
    UITabBarItem *item0  = [tabBar.items objectAtIndex:0];
    UITabBarItem *item1  = [tabBar.items objectAtIndex:1];
    UITabBarItem *item2  = [tabBar.items objectAtIndex:2];
    UITabBarItem *item3  = [tabBar.items objectAtIndex:3];

    
    [item0 setFinishedSelectedImage:selectedImage0 withFinishedUnselectedImage:unselectedImage0];
    [item1 setFinishedSelectedImage:selectedImage1 withFinishedUnselectedImage:unselectedImage1];
    [item2 setFinishedSelectedImage:selectedImage2 withFinishedUnselectedImage:unselectedImage2];
    [item3 setFinishedSelectedImage:selectedImage3 withFinishedUnselectedImage:unselectedImage3];
}



-(void)changeBackgroundTabbar{
   /* UIImage* tabBarBackground = [UIImage imageNamed:@"tabbar.png"];
    [[UITabBar appearance] setBackgroundImage:tabBarBackground];
    
    [[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageNamed:@"selection-tab.png"]];*/
}






-(void)createAllDirectory{
    NSString *PrivatDoc = [LIBRARY stringByAppendingPathComponent:@"Private Documents"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:PrivatDoc]) {
        [self createPrivateFolder];
    }
    
    NSString *dbPath = [LIBRARY stringByAppendingPathComponent:@"Private Documents/DataBase"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dbPath]) {
        [self createDBFolder];
    }
    
    
    NSString *ImgAppsPath = [LIBRARY stringByAppendingPathComponent:@"Private Documents/images"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:ImgAppsPath]) {
        [self createAppsImagesFolder];
    }
    
    
}

-(void)createDBFolder{
    NSString *folderPath = [LIBRARY stringByAppendingPathComponent:@"Private Documents/DataBase"];
    [[NSFileManager defaultManager] createDirectoryAtPath:folderPath
                              withIntermediateDirectories:YES
                                               attributes:nil
                                                    error:nil];
    NSURL *pathURL= [NSURL fileURLWithPath:folderPath];
    [self addSkipBackupAttributeToItemAtURL:pathURL];
}

-(void)createPrivateFolder{
    NSString *folderPrivat = [LIBRARY stringByAppendingPathComponent:@"Private Documents"];
    [[NSFileManager defaultManager] createDirectoryAtPath:folderPrivat
                              withIntermediateDirectories:YES
                                               attributes:nil
                                                    error:nil];
    NSURL *pathURL= [NSURL fileURLWithPath:folderPrivat];
    [self addSkipBackupAttributeToItemAtURL:pathURL];
}



-(void)createAppsImagesFolder{
    NSString *folderAppsImg = [LIBRARY stringByAppendingPathComponent:@"Private Documents/images"];
    [[NSFileManager defaultManager] createDirectoryAtPath:folderAppsImg
                              withIntermediateDirectories:YES
                                               attributes:nil
                                                    error:nil];
    NSURL *pathURL= [NSURL fileURLWithPath:folderAppsImg];
    [self addSkipBackupAttributeToItemAtURL:pathURL];
}

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL*)URL {
    const char* filePath = [[URL path] fileSystemRepresentation];
    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;
    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    return result == 0;
}












- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
